import React, { createContext, useContext, useState, useEffect } from 'react';
import { api } from './api';

interface UserContextType {
  email: string | null;
  setEmail: (email: string | null) => void;
  isLoggedIn: boolean;
  login: (email: string) => void;
  logout: () => void;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

export const UserProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [email, setEmail] = useState<string | null>(localStorage.getItem('userEmail'));
  const [isLoggedIn, setIsLoggedIn] = useState<boolean>(!!localStorage.getItem('token'));

  useEffect(() => {
    // 验证 token 是否有效
    const verifyAuth = async () => {
      if (localStorage.getItem('token')) {
        const isValid = await api.verifyToken();
        if (!isValid) {
          logout();
        }
      }
    };

    verifyAuth();
  }, []);

  const login = (newEmail: string) => {
    setEmail(newEmail);
    setIsLoggedIn(true);
    localStorage.setItem('userEmail', newEmail);
  };

  const logout = () => {
    setEmail(null);
    setIsLoggedIn(false);
    api.logout();
  };

  return (
    <UserContext.Provider value={{ email, setEmail, isLoggedIn, login, logout }}>
      {children}
    </UserContext.Provider>
  );
};

export const useUser = () => {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
}; 